<template>
	<view style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: white; z-index: -1;"></view>
	<view class="index-container">
		<!-- 头部区域 -->
		<view class="header-section" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="user-greeting">
				<view class="greeting-text">
					<text class="greeting-time">{{ greetingTime }}</text>
					<text class="greeting-name">{{ userInfo.nickname || '访客' }}</text>
				</view>
				<view class="user-avatar" @click="goToProfile">
					<text class="avatar-text">{{ getAvatarText() }}</text>
				</view>
			</view>
			

		</view>
		
		<!-- 搜索和筛选区域 -->
		<view class="search-filter-section">
			<view class="search-box" :class="{ searching: isSearching }">
				<view class="search-icon">
					<text v-if="!isSearching">🔍</text>
					<text v-else class="searching-icon">⏳</text>
				</view>
				<input 
					class="search-input" 
					placeholder="搜索待办事项..." 
					v-model="searchKeyword"
					@input="onSearchInput"
					@focus="isSearching = true"
					@blur="isSearching = false"
				/>
				<view v-if="searchKeyword" class="clear-search" @click="clearSearch">✕</view>
			</view>
			
			<!-- 日期快捷方式 -->
			<view class="date-filter-section">
				<scroll-view scroll-x class="date-tabs-scroll">
					<view class="date-tabs">
						<view 
							v-for="date in dateOptions" 
							:key="date.key"
							class="date-tab"
							:class="{ active: currentDateFilter === date.key }"
							@click="setDateFilter(date.key)"
						>
							<text class="date-icon">{{ date.icon }}</text>
							<text class="date-label">{{ date.label }}</text>
							<text class="date-text">{{ date.date }}</text>
						</view>
						
						<!-- 自定义日期选择 -->
						<picker 
							mode="date" 
							:value="selectedDate" 
							:start="minDate"
							:end="maxDate"
							@change="onDateChange"
						>
							<view 
								class="date-tab custom-date-tab"
								:class="{ active: currentDateFilter === 'custom' }"
							>
								<text class="date-icon">🗓️</text>
								<text class="date-label">自定义</text>
								<text class="date-text">{{ customDateText }}</text>
							</view>
						</picker>
					</view>
				</scroll-view>
			</view>
			


			<view class="ai-summary-card" @click="showAiSummary">
				<view class="ai-summary-header">
					<text class="ai-icon">🤖</text>
					<text class="ai-title">AI智能总结</text>
					<text class="ai-arrow"></text>
				</view>
				<text class="ai-description">让AI为您总结今日待办完成情况</text>
			</view>
		</view>
		
		<!-- 待办事项列表 -->
		<scroll-view 
			scroll-y 
			class="todo-list-container" 
			@scrolltolower="loadMore"
		>
			<view v-if="loading && todoList.length === 0" class="loading-state">
				<view class="loading-icon">⏳</view>
				<text class="loading-text">正在加载...</text>
			</view>
			
			<view v-else-if="filteredTodoList.length === 0" class="empty-state">
				<view class="empty-icon">📝</view>
				<text class="empty-title">{{ getEmptyStateText() }}</text>
				<text class="empty-subtitle">{{ getEmptyStateSubtext() }}</text>
				<view class="empty-action" @click="goToAdd">
					<text class="empty-action-text">创建第一个待办</text>
				</view>
			</view>
			
			<view v-else class="todo-list">
				<view 
					v-for="todo in filteredTodoList" 
					:key="todo.id" 
					class="todo-item"
					:class="{ 
						completed: todo.completed,
						overdue: isOverdue(todo)
					}"
					@click="goToDetail(todo.id)"
				>
					<view class="todo-checkbox" @click.stop="toggleTodo(todo.id)">
						<view class="checkbox-inner" :class="{ checked: todo.completed }">
							<text v-if="todo.completed" class="check-mark">✓</text>
						</view>
					</view>
					
					<view class="todo-content">
						<view class="todo-title" :class="{ completed: todo.completed }">
							{{ todo.title }}
						</view>
						<view v-if="todo.description" class="todo-description">
							{{ todo.description }}
						</view>
						<view class="todo-meta">
							<text v-if="todo.dueTime" class="todo-date" :class="{ overdue: isOverdue(todo) }">
								{{ formatTimeHHMM(todo.dueTime) }}
							</text>
							<view v-if="isOverdue(todo) && !todo.completed" class="todo-status overdue-status">
								已过期
							</view>
							<view v-if="todo.priority" class="todo-priority" :class="'priority-' + todo.priority">
								{{ getPriorityText(todo.priority) }}
							</view>
						</view>
					</view>
					
					<view class="todo-actions">
						<view class="action-btn edit-btn" @click.stop="goToEdit(todo.id)">
							<text class="action-icon">✏️</text>
						</view>
						<view class="action-btn delete-btn" @click.stop="confirmDelete(todo.id)">
							<text class="action-icon">🗑️</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view v-if="hasMore && filteredTodoList.length > 0" class="load-more">
				<text class="load-more-text">上拉加载更多</text>
			</view>
		</scroll-view>
		
		<!-- 浮动按钮组 -->
		<view class="fab-container">
			<!-- 主添加按钮 -->
			<view class="fab-button main-fab" @click="goToAdd">
				<text class="fab-icon">+</text>
			</view>
			
			<!-- 诊断按钮（仅开发模式显示） -->
			<view v-if="isDevelopment" class="fab-button diagnosis-fab" @click="runDiagnosis">
				<text class="fab-icon diagnosis-icon">🔍</text>
			</view>
		</view>
		

	</view>
</template>

<script>
	import { completeTodo, uncompleteTodo, deleteTodo, searchTodos } from '../../api/todo'
	import { formatDate, isOverdue, getCurrentChinaTime, createDate, formatTimeHHMM } from '../../utils/date'
	import { runDiagnostics } from '../../utils/apiTest'
	import appConfig from '../../utils/config'
	
	export default {
		data() {
			return {
				statusBarHeight: 0,
				userInfo: {},
				todoList: [],
				searchKeyword: '',
				currentFilter: 'all',
				currentDateFilter: 'today',
				hasMore: false,
				loading: false,
				isSearching: false,
				searchTimer: null,
				originalTodoList: [], // 保存原始数据，用于搜索后的恢复

				dateOptions: [],
				// 自定义日期相关
				customDate: '',
				// 日期选择器相关
				selectedDate: '',
				minDate: '',
				maxDate: '',
				// 双击刷新相关
				lastTabClickTime: 0,
				tabClickCount: 0,
				// 开发模式标识
				isDevelopment: appConfig.DEBUG
			}
		},
		computed: {
			greetingTime() {
				// 使用 date.js 获取当前东八区时间
				const currentTime = getCurrentChinaTime();
				const hour = createDate(currentTime).getHours();
				if (hour < 6) return '夜深了';
				if (hour < 12) return '早上好';
				if (hour < 18) return '下午好';
				return '晚上好';
			},
			
			customDateText() {
				if (this.customDate) {
					return this.formatCustomDateText(this.customDate);
				}
				return '选择日期';
			},
			

			

			
			filteredTodoList() {
				// 现在搜索和筛选都由后端处理，直接返回todoList
				// 只需要在前端做简单的排序优化
				return this.todoList.sort((a, b) => {
					// 未完成的待办排在前面
					if (a.completed !== b.completed) {
						return a.completed ? 1 : -1;
					}
									// 按创建时间降序排列
				const dateA = a.createTime ? createDate(a.createTime) : new Date(0);
				const dateB = b.createTime ? createDate(b.createTime) : new Date(0);
				return dateB - dateA;
				});
			}
		},
		
		onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			
			// 初始化日期选项
			this.initDateOptions();
			
			// 初始化日期选择器
			this.initSimpleDatePicker();
		},
		
		onShow() {
			// 检查登录状态，如果未登录则不继续执行
			if (!this.checkLogin()) {
				return;
			}
			
			// 每次打开APP都默认选中今天
			this.currentDateFilter = 'today';
			this.customDate = '';
			
			// 保存当前日期状态
			uni.setStorageSync('currentDateFilter', 'today');
			uni.removeStorageSync('customDate');
			
			// 加载今天的数据
			this.loadTodosByDate('today');
		},
		
		onUnload() {
			// 页面销毁时清理定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
		},
		
		// 监听底部tabBar点击事件
		onTabItemTap(item) {
			// 只监听首页tab的点击
			if (item.index === 0) {
				this.handleHomeTabClick();
			}
		},
		
		methods: {
			// 获取头像显示文字
			getAvatarText() {
				if (this.userInfo.nickname) {
					// 如果有昵称，显示昵称的最后一个字符
					return this.userInfo.nickname.slice(-1);
				} else if (this.userInfo.phone) {
					// 如果没有昵称但有手机号，显示手机号后4位
					return this.userInfo.phone.slice(-4);
				} else {
					// 都没有则显示默认字符
					return 'U';
				}
			},
			
			// 格式化时间为HH:mm格式
			formatTimeHHMM(timeStr) {
				return formatTimeHHMM(timeStr);
			},
			
			checkLogin() {
				const isLoggedIn = uni.getStorageSync('isLoggedIn');
				if (!isLoggedIn) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
					return false;
				}
				this.userInfo = uni.getStorageSync('userInfo') || {};
				return true;
			},
			

			
			onSearchInput() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				
				// 防抖处理，500ms后执行搜索
				this.searchTimer = setTimeout(() => {
					this.performSearch();
				}, 500);
			},
			
			async performSearch() {
				const keyword = this.searchKeyword.trim();
				
				if (keyword === '') {
					// 如果搜索关键词为空，恢复到当前日期的数据
					this.isSearching = false;
					await this.loadTodosByDate(this.currentDateFilter);
					return;
				}
				
				try {
					this.isSearching = true;
					this.loading = true;
					
					// 根据当前筛选状态确定status参数
					let status = null;
					if (this.currentFilter === 'pending') {
						status = 0;
					} else if (this.currentFilter === 'completed') {
						status = 1;
					}
					
					// 调用搜索API
					const response = await searchTodos(keyword, status);
					
					if (response && response.code === 200) {
						this.todoList = response.data || [];
					} else {
						console.error('搜索失败:', response);
						uni.showToast({
							title: '搜索失败，请重试',
							icon: 'none',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('搜索异常:', error);
					uni.showToast({
						title: '搜索失败，请检查网络',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.loading = false;
				}
			},
			
			clearSearch() {
				this.searchKeyword = '';
				this.isSearching = false;
				// 清除定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				// 重新加载当前日期的数据
				this.loadTodosByDate(this.currentDateFilter);
			},
			

			
			getEmptyStateText() {
				if (this.searchKeyword) return '没有找到相关待办';
				if (this.currentFilter === 'completed') return '还没有完成的待办';
				if (this.currentFilter === 'pending') return '太棒了！所有待办都已完成';
				return '还没有待办';
			},
			
			getEmptyStateSubtext() {
				if (this.searchKeyword) return '尝试使用其他关键词搜索';
				if (this.currentFilter === 'completed') return '完成一些待办来查看进度';
				if (this.currentFilter === 'pending') return '继续保持这个好习惯';
				return '创建您的第一个待办事项';
			},
			
			async toggleTodo(id) {
				const todo = this.todoList.find(t => t.id === id);
				if (!todo) {
					console.error('未找到对应的待办事项:', id);
					uni.showToast({
						title: '待办事项不存在',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				// 显示加载状态
				uni.showLoading({
					title: '更新中...'
				});
				
				try {
					console.log('开始更新待办状态:', id, '当前状态:', todo.completed);
					
					// 调用后端API
					let response;
					if (todo.completed) {
						response = await uncompleteTodo(id);
					} else {
						response = await completeTodo(id);
					}
					
					console.log('API响应:', response);
					
					// 检查响应
					if (response && response.code === 200) {
						// 更新本地状态
						todo.completed = !todo.completed;
						
						// 显示反馈
						uni.showToast({
							title: todo.completed ? '待办已完成' : '待办已恢复',
							icon: 'success',
							duration: 1500
						});
						
						// 更新本地存储作为备份
						uni.setStorageSync('todoList', this.todoList);
					} else {
						// API返回错误
						console.error('API返回错误:', response);
						uni.showToast({
							title: response?.message || '更新失败',
							icon: 'none',
							duration: 2000
						});
					}
					
				} catch (error) {
					console.error('更新待办状态失败:', error);
					
					// 更详细的错误处理
					let errorMessage = '操作失败，请重试';
					
					if (error.message) {
						if (error.message.includes('timeout')) {
							errorMessage = '请求超时，请检查网络';
						} else if (error.message.includes('401') || error.message.includes('未授权')) {
							errorMessage = '登录已过期，请重新登录';
							// 清除登录状态，跳转到登录页
							uni.removeStorageSync('isLoggedIn');
							uni.removeStorageSync('token');
							uni.removeStorageSync('userInfo');
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/login/login'
								});
							}, 1500);
						} else if (error.message.includes('网络')) {
							errorMessage = '网络连接失败，请检查网络';
						} else {
							errorMessage = `操作失败: ${error.message}`;
						}
					}
					
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			confirmDelete(id) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个待办事项吗？此操作无法撤销。',
					confirmColor: '#fa3534',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用后端API删除
								await deleteTodo(id);
								
								// 从本地列表中删除
							this.todoList = this.todoList.filter(t => t.id !== id);
								
								// 更新本地存储
							uni.setStorageSync('todoList', this.todoList);
								
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							} catch (error) {
								console.error('删除待办失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
				});
			},
			
			// 使用统一的日期格式化方法
			formatDate,
			isOverdue,
			getCurrentChinaTime,
			createDate,
			


			getPriorityText(priority) {
				const map = {
					high: '高优先级',
					medium: '中优先级',
					low: '低优先级'
				};
				return map[priority] || '';
			},
			
			loadMore() {
				// 加载更多数据的逻辑
				// 这里可以实现分页加载
			},
			

			
			goToAdd() {
				uni.navigateTo({ url: '/pages/add/add' });
			},
			
			goToEdit(id) {
				uni.navigateTo({ url: `/pages/add/add?id=${id}` });
			},
			
			goToDetail(id) {
				console.log('goToDetail', id);
				uni.navigateTo({ url: `/pages/detail/detail?id=${id}` });
			},
			
			goToProfile() {
				uni.navigateTo({ url: '/pages/profile/profile' });
			},
			
			// 初始化日期选项
			initDateOptions() {
				// 使用 date.js 获取当前东八区时间，修复时区问题
				const currentTime = getCurrentChinaTime();
				const today = createDate(currentTime);
				const yesterday = new Date(today);
				yesterday.setDate(yesterday.getDate() - 1);
				const tomorrow = new Date(today);
				tomorrow.setDate(tomorrow.getDate() + 1);
				const dayAfterTomorrow = new Date(today);
				dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
				
				this.dateOptions = [
					{
						key: 'yesterday',
						label: '昨天',
						date: this.formatDisplayDate(yesterday),
						icon: '📊'
					},
					{
						key: 'today',
						label: '今天',
						date: this.formatDisplayDate(today),
						icon: '⭐'
					},
					{
						key: 'tomorrow',
						label: '明天',
						date: this.formatDisplayDate(tomorrow),
						icon: '⏰'
					},
					{
						key: 'dayAfterTomorrow',
						label: '后天',
						date: this.formatDisplayDate(dayAfterTomorrow),
						icon: '📅'
					}
				];
			},
			
			// 格式化显示日期
			formatDisplayDate(date) {
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${month}/${day}`;
			},
			
			// 获取日期对应的API参数
			getDateParam(dateKey) {
				// 使用 date.js 获取当前东八区时间，修复时区问题
				const currentTime = getCurrentChinaTime();
				console.log('currentTime', currentTime);
				const today = createDate(currentTime);
				const date = new Date(today);
				
				console.log('dateKey', dateKey);

				switch(dateKey) {
					case 'yesterday':
						date.setDate(date.getDate() - 1);
						break;
					case 'today':
						// 保持今天
						break;
					case 'tomorrow':
						date.setDate(date.getDate() + 1);
						break;
					case 'dayAfterTomorrow':
						date.setDate(date.getDate() + 2);
						break;
					default:
						return null;
				}
				console.log('date.toISOString()', date.toISOString());
				return date.toISOString().split('T')[0]; // YYYY-MM-DD格式
			},
			
			// 设置日期筛选
			async setDateFilter(dateKey) {
				this.currentDateFilter = dateKey;
				
				// 保存日期状态到本地存储
				uni.setStorageSync('currentDateFilter', dateKey);
				
				// 根据日期获取数据
				await this.loadTodosByDate(dateKey);
			},
			
			// 初始化简单日期选择器
			initSimpleDatePicker() {
				// 使用 date.js 获取当前东八区时间
				const currentTime = getCurrentChinaTime();
				const today = createDate(currentTime);
				const currentYear = today.getFullYear();
				
				// 设置日期范围（前后各2年）
				const minYear = currentYear - 2;
				const maxYear = currentYear + 2;
				
				this.minDate = `${minYear}-01-01`;
				this.maxDate = `${maxYear}-12-31`;
				this.selectedDate = today.toISOString().split('T')[0];
			},
			

			
			// 处理日期选择
			onDateChange(e) {
				const dateStr = e.detail.value;
				this.setCustomDate(dateStr);
			},			

			
			// 验证日期格式
			isValidDate(dateStr) {
				const regex = /^\d{4}-\d{2}-\d{2}$/;
				if (!regex.test(dateStr)) return false;
				
				const date = new Date(dateStr);
				return date instanceof Date && !isNaN(date) && dateStr === date.toISOString().split('T')[0];
			},
			
			// 设置自定义日期
			async setCustomDate(dateStr) {
				this.customDate = dateStr;
				this.customDateText = this.formatCustomDateText(dateStr);
				this.currentDateFilter = 'custom';
				
				// 保存自定义日期状态到本地存储
				uni.setStorageSync('currentDateFilter', 'custom');
				uni.setStorageSync('customDate', dateStr);
				
				// 加载自定义日期的数据
				await this.loadCustomDateTodos(dateStr);
			},
			
			// 格式化自定义日期显示文本
			formatCustomDateText(dateStr) {
				const date = new Date(dateStr);
				// 使用 date.js 获取当前东八区时间
				const currentTime = getCurrentChinaTime();
				const today = createDate(currentTime);
				const yesterday = new Date(today);
				yesterday.setDate(yesterday.getDate() - 1);
				const tomorrow = new Date(today);
				tomorrow.setDate(tomorrow.getDate() + 1);
				
				const targetDateStr = date.toISOString().split('T')[0];
				const todayStr = today.toISOString().split('T')[0];
				const yesterdayStr = yesterday.toISOString().split('T')[0];
				const tomorrowStr = tomorrow.toISOString().split('T')[0];
				
				if (targetDateStr === todayStr) return '今天';
				if (targetDateStr === yesterdayStr) return '昨天';
				if (targetDateStr === tomorrowStr) return '明天';
				
				// 返回月/日格式
				const month = date.getMonth() + 1;
				const day = date.getDate();
				return `${month}/${day}`;
			},
			
			// 加载自定义日期的待办事项
			async loadCustomDateTodos(dateStr) {
				try {
					this.loading = true;
					
					// 调用后端API获取指定日期的待办事项
					const { getTodosByDate } = await import('../../api/todo');
					const response = await getTodosByDate(dateStr);
					console.log('自定义日期请求数据response', JSON.stringify(response));
					
					if (response && response.code === 200) {
						let todoList = response.data || [];
						
						// 根据当前筛选条件过滤数据
						if (this.currentFilter === 'pending') {
							todoList = todoList.filter(t => !t.completed);
						} else if (this.currentFilter === 'completed') {
							todoList = todoList.filter(t => t.completed);
						}
						
						this.todoList = todoList;
						// 保存原始数据
						this.originalTodoList = [...response.data];
					} else {
						console.error('获取自定义日期待办事项失败:', response);
						uni.showToast({
							title: response?.message || '获取数据失败',
							icon: 'none',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('加载自定义日期待办事项异常:', error);
					uni.showToast({
						title: '网络连接失败',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 根据日期加载待办事项
			async loadTodosByDate(dateKey) {
				
				try {
					this.loading = true;
					
					let date;
					if (dateKey === 'custom') {
						// 如果是自定义日期，直接使用customDate
						date = this.customDate;
					} else {
						// 否则通过dateKey计算日期
						date = this.getDateParam(dateKey);
					}
					
					console.log('date', date);
					if (!date) return;
					
					// 调用后端API获取指定日期的待办事项
					const { getTodosByDate } = await import('../../api/todo');
					const response = await getTodosByDate(date);
					console.log('请求数据response', JSON.stringify(response));
					
					if (response && response.code === 200) {
						let todoList = response.data || [];
						
						// 根据当前筛选条件过滤数据
						if (this.currentFilter === 'pending') {
							todoList = todoList.filter(t => !t.completed);
						} else if (this.currentFilter === 'completed') {
							todoList = todoList.filter(t => t.completed);
						}
						
						this.todoList = todoList;
						// 保存原始数据
						this.originalTodoList = [...response.data];
					} else {
						console.error('获取日期待办事项失败:', response);
						uni.showToast({
							title: response?.message || '获取数据失败',
							icon: 'none',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('加载日期待办事项异常:', error);
					uni.showToast({
						title: '网络连接失败',
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 显示AI总结
			showAiSummary() {
				uni.navigateTo({
					url: '/pages/ai-summary/ai-summary'
				});
			},
			
			// 处理首页tab双击刷新
			handleHomeTabClick() {
				const currentTime = Date.now();
				const timeDiff = currentTime - this.lastTabClickTime;
				
				// 如果两次点击间隔小于500ms，认为是双击
				if (timeDiff < 500) {
					this.tabClickCount++;
					
					// 如果是第二次点击，执行刷新
					if (this.tabClickCount >= 2) {
						this.performRefresh();
						// 重置计数
						this.tabClickCount = 0;
						this.lastTabClickTime = 0;
						return;
					}
				} else {
					// 重置计数
					this.tabClickCount = 1;
				}
				
				this.lastTabClickTime = currentTime;
			},
			
			// 执行刷新操作
			async performRefresh() {
				try {
					// 显示刷新提示
					uni.showToast({
						title: '正在刷新...',
						icon: 'loading',
						duration: 1500,
						mask: true
					});
					
					// 清空搜索关键词和筛选条件
					this.searchKeyword = '';
					this.currentFilter = 'all';
					
					// 重新加载当前选中日期的数据
					await this.loadTodosByDate(this.currentDateFilter);
					
					// 显示刷新完成提示
					uni.showToast({
						title: '已刷新',
						icon: 'success',
						duration: 800
					});
				} catch (error) {
					console.error('刷新失败:', error);
					uni.showToast({
						title: '刷新失败',
						icon: 'error',
						duration: 1500
					});
				}
			},
			
			// 运行诊断（仅开发模式）
			async runDiagnosis() {
				if (!this.isDevelopment) {
					return;
				}
				
				uni.showLoading({
					title: '诊断中...'
				});
				
				try {
					// 获取第一个待办事项进行测试
					const testTodoId = this.todoList.length > 0 ? this.todoList[0].id : null;
					
					const { results, report } = await runDiagnostics(testTodoId);
					
					uni.hideLoading();
					
					// 显示诊断结果
					const content = `${report.summary}\n\n问题:\n${report.issues.join('\n')}\n\n建议:\n${report.recommendations.join('\n')}`;
					
					uni.showModal({
						title: 'API诊断报告',
						content: content,
						showCancel: false,
						confirmText: '确定'
					});
					
					console.log('完整诊断结果:', results);
					
				} catch (error) {
					uni.hideLoading();
					console.error('诊断过程出错:', error);
					uni.showToast({
						title: '诊断失败',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style>
	.index-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: white !important;
		margin: 0;
		padding: 0;
	}
	
	/* 头部区域 */
	.header-section {
		padding: 30rpx 30rpx 100rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		position: relative;
		overflow: hidden;
		box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.15);
	}
	
	.header-section::before {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 2rpx;
		background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%);
		z-index: 2;
	}
	
	.header-section::after {
		content: '';
		position: absolute;
		top: -30%;
		right: -15%;
		width: 300rpx;
		height: 300rpx;
		background: rgba(255, 255, 255, 0.08);
		border-radius: 50%;
		z-index: 1;
	}
	
	.user-greeting {
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		z-index: 2;
	}
	
	.greeting-text {
		display: flex;
		flex-direction: column;
	}
	
	.greeting-time {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
		margin-bottom: 8rpx;
		font-weight: 400;
	}
	
	.greeting-name {
		font-size: 34rpx;
		font-weight: 600;
		color: white;
		letter-spacing: 0.5rpx;
	}
	
	.user-avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.2);
		border: 2rpx solid rgba(255, 255, 255, 0.3);
		backdrop-filter: blur(10rpx);
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.user-avatar:active {
		transform: scale(0.95);
		background: rgba(255, 255, 255, 0.3);
	}
	
	.avatar-text {
		color: white;
		font-size: 28rpx;
		font-weight: 600;
		text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
	}
	

	
	/* 搜索和筛选区域 */
	.search-filter-section {
		background: white !important;
		background-color: white !important;
		border-radius: 32rpx 32rpx 0 0;
		padding: 35rpx 30rpx 25rpx;
		margin-top: -70rpx;
		box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.08);
		position: relative;
		z-index: 10;
	}
	
	.search-box {
		display: flex;
		align-items: center;
		background: #f1f5f9;
		border-radius: 20rpx;
		padding: 18rpx 20rpx;
		margin-bottom: 25rpx;
		transition: all 0.3s ease;
		border: 2rpx solid transparent;
	}
	
	.search-box.searching {
		background: #eff6ff;
		border-color: #3b82f6;
		box-shadow: 0 0 0 4rpx rgba(59, 130, 246, 0.1);
	}
	
	.search-icon {
		font-size: 26rpx;
		margin-right: 12rpx;
		color: #64748b;
		transition: color 0.3s ease;
	}
	
	.searching-icon {
		animation: spin 1s linear infinite;
		color: #3b82f6 !important;
	}
	
	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #1e293b;
		font-weight: 400;
	}
	
	.search-input::placeholder {
		color: #94a3b8;
	}
	
	.clear-search {
		font-size: 22rpx;
		color: #64748b;
		padding: 8rpx;
		border-radius: 50%;
		background: rgba(100, 116, 139, 0.1);
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
	}
	
	.clear-search:active {
		background: rgba(100, 116, 139, 0.2);
		transform: scale(0.9);
	}
	
	/* 日期筛选样式 */
	.date-filter-section {
		margin-bottom: 20rpx;
	}
	
	.date-tabs-scroll {
		white-space: nowrap;
	}
	
	.date-tabs {
		display: flex;
		gap: 12rpx;
		padding: 0;
	}
	
	.date-tab {
		flex-shrink: 0;
		background: #f1f5f9;
		padding: 16rpx 20rpx;
		border-radius: 14rpx;
		min-width: 120rpx;
		text-align: center;
		transition: all 0.3s ease;
		border: 2rpx solid transparent;
		position: relative;
		overflow: hidden;
	}
	
	.date-tab.active {
		background: #3b82f6;
		border-color: #3b82f6;
		transform: translateY(-1rpx);
		box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
	}
	
	.date-icon {
		font-size: 28rpx;
		display: block;
		margin-bottom: 6rpx;
		opacity: 0.8;
	}
	
	.date-tab.active .date-icon {
		opacity: 1;
	}
	
	.date-label {
		font-size: 22rpx;
		font-weight: 500;
		color: #475569;
		display: block;
		margin-bottom: 2rpx;
	}
	
	.date-tab.active .date-label {
		color: white;
	}
	
	.date-text {
		font-size: 18rpx;
		color: #94a3b8;
		display: block;
		font-weight: 400;
	}
	
	.date-tab.active .date-text {
		color: rgba(255, 255, 255, 0.8);
	}
	
	/* 自定义日期选择器样式 */
	.custom-date-tab {
		border: 2rpx dashed #cbd5e1;
		background: #fafafa !important;
	}
	
	.custom-date-tab.active {
		border-color: #3b82f6;
		background: #3b82f6 !important;
		border-style: solid;
	}

	.ai-summary-card {
		margin-top: 10rpx;
		background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
		border-radius: 20rpx;
		padding: 28rpx;
		color: white;
		position: relative;
		overflow: hidden;
		transition: all 0.3s ease;
		box-shadow: 0 8rpx 32rpx rgba(99, 102, 241, 0.25);
		transform: translateY(-5rpx);
	}
	
	.ai-summary-card:active {
		transform: scale(0.98);
		box-shadow: 0 6rpx 25rpx rgba(99, 102, 241, 0.3);
	}
	
	.ai-summary-card::before {
		content: '';
		position: absolute;
		top: -30%;
		right: -15%;
		width: 120rpx;
		height: 120rpx;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 50%;
		z-index: 1;
	}
	
	.ai-summary-header {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;
		position: relative;
		z-index: 2;
	}
	
	.ai-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
	}
	
	.ai-title {
		flex: 1;
		font-size: 26rpx;
		font-weight: 600;
		letter-spacing: 0.3rpx;
	}
	
	.ai-arrow {
		font-size: 20rpx;
		opacity: 0.8;
		transform: rotate(-45deg);
		transition: transform 0.3s ease;
	}
	
	.ai-summary-card:active .ai-arrow {
		transform: rotate(-45deg) translateX(2rpx);
	}
	
	.ai-description {
		font-size: 22rpx;
		opacity: 0.9;
		line-height: 1.4;
		position: relative;
		z-index: 2;
		font-weight: 400;
	}
	
	/* 待办事项列表 */
	.todo-list-container {
		flex: 1;
		background: white !important;
		background-color: white !important;
		padding: 0;
		overflow: hidden;
		position: relative;
		z-index: 8;
		border-radius: 0 0 0 0;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
	}
	
	/* 加载状态 */
	.loading-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 40rpx;
		text-align: center;
	}
	
	.loading-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
		opacity: 0.6;
		animation: spin 2s linear infinite;
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #64748b;
		font-weight: 400;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 40rpx;
		text-align: center;
	}
	
	.empty-icon {
		font-size: 100rpx;
		margin-bottom: 24rpx;
		opacity: 0.4;
		filter: grayscale(0.3);
	}
	
	.empty-title {
		font-size: 30rpx;
		color: #1e293b;
		margin-bottom: 12rpx;
		font-weight: 600;
	}
	
	.empty-subtitle {
		font-size: 24rpx;
		color: #64748b;
		margin-bottom: 32rpx;
		line-height: 1.5;
		font-weight: 400;
	}
	
	.empty-action {
		background: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
		color: white;
		padding: 16rpx 32rpx;
		border-radius: 20rpx;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.3);
	}
	
	.empty-action:active {
		transform: scale(0.95);
		box-shadow: 0 6rpx 16rpx rgba(59, 130, 246, 0.4);
	}
	
	.empty-action-text {
		font-size: 26rpx;
		color: white;
		font-weight: 500;
	}
	
	.todo-list {
		padding: 0 30rpx 150rpx;
	}
	
	.todo-item {
		display: flex;
		align-items: flex-start;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f1f5f9;
		transition: all 0.3s ease;
		position: relative;
	}
	
	.todo-item:last-child {
		border-bottom: none;
	}
	
	.todo-item:active {
		background: #f1f5f9;
		margin: 0 -30rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		border-radius: 12rpx;
	}
	
	.todo-item.overdue {
		background: rgba(239, 68, 68, 0.05);
		border-left: 4rpx solid #ef4444;
		margin: 0 -30rpx;
		padding-left: 26rpx;
		padding-right: 30rpx;
		border-radius: 0 12rpx 12rpx 0;
	}
	
	.todo-item.overdue:active {
		background: rgba(239, 68, 68, 0.08);
	}
	
	.todo-checkbox {
		margin-right: 16rpx;
		margin-top: 4rpx;
	}
	
	.checkbox-inner {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #cbd5e1;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		background: white;
	}
	
	.checkbox-inner.checked {
		background: linear-gradient(135deg, #10b981 0%, #059669 100%);
		border-color: #10b981;
		box-shadow: 0 2rpx 8rpx rgba(16, 185, 129, 0.3);
	}
	
	.check-mark {
		color: white;
		font-size: 20rpx;
		font-weight: bold;
	}
	
	.todo-content {
		flex: 1;
		margin-right: 16rpx;
	}
	
	.todo-title {
		font-size: 28rpx;
		color: #1e293b;
		line-height: 1.4;
		margin-bottom: 6rpx;
		font-weight: 500;
		letter-spacing: 0.2rpx;
	}
	
	.todo-title.completed {
		text-decoration: line-through;
		color: #94a3b8;
	}
	
	.todo-description {
		font-size: 24rpx;
		color: #64748b;
		line-height: 1.4;
		margin-bottom: 12rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		font-weight: 400;
	}
	
	.todo-meta {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}
	
	.todo-date {
		font-size: 20rpx;
		color: #94a3b8;
		font-weight: 400;
	}
	
	.todo-date.overdue {
		color: #ef4444;
		font-weight: 500;
	}
	
	.todo-status {
		font-size: 18rpx;
		padding: 3rpx 8rpx;
		border-radius: 8rpx;
		font-weight: 500;
	}
	
	.overdue-status {
		background: #ef4444;
		color: white;
	}
	
	.todo-priority {
		font-size: 18rpx;
		padding: 3rpx 8rpx;
		border-radius: 8rpx;
		color: white;
		font-weight: 500;
	}
	
	.priority-high {
		background: #ef4444;
	}
	
	.priority-medium {
		background: #f59e0b;
	}
	
	.priority-low {
		background: #10b981;
	}
	
	.todo-actions {
		display: flex;
		gap: 8rpx;
	}
	
	.action-btn {
		width: 52rpx;
		height: 52rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f1f5f9;
		border: 1rpx solid #e2e8f0;
		transition: all 0.3s ease;
	}
	
	.action-icon {
		font-size: 20rpx;
		opacity: 0.8;
	}
	
	.edit-btn:active {
		background: #dbeafe;
		border-color: #3b82f6;
		transform: scale(0.95);
	}
	
	.edit-btn:active .action-icon {
		opacity: 1;
	}
	
	.delete-btn:active {
		background: #fee2e2;
		border-color: #ef4444;
		transform: scale(0.95);
	}
	
	.delete-btn:active .action-icon {
		opacity: 1;
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.load-more-text {
		font-size: 24rpx;
		color: #94a3b8;
		font-weight: 400;
	}
	
	/* 浮动按钮组 */
	.fab-container {
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		z-index: 100;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}
	
	.fab-button {
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}
	
	.fab-button::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, transparent 100%);
		border-radius: 50%;
	}
	
	.fab-button:active {
		transform: scale(0.95);
	}
	
	/* 主添加按钮 */
	.main-fab {
		width: 112rpx;
		height: 112rpx;
		background: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
		box-shadow: 0 8rpx 25rpx rgba(59, 130, 246, 0.4);
	}
	
	.main-fab:active {
		box-shadow: 0 6rpx 20rpx rgba(59, 130, 246, 0.5);
	}
	
	/* 诊断按钮 */
	.diagnosis-fab {
		width: 90rpx;
		height: 90rpx;
		background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
		box-shadow: 0 6rpx 20rpx rgba(245, 158, 11, 0.3);
	}
	
	.diagnosis-fab:active {
		box-shadow: 0 4rpx 15rpx rgba(245, 158, 11, 0.4);
	}
	
	.fab-icon {
		color: white;
		font-weight: 300;
		position: relative;
		z-index: 2;
		line-height: 1;
	}
	
	.main-fab .fab-icon {
		font-size: 44rpx;
	}
	
	.diagnosis-icon {
		font-size: 32rpx;
	}
	

	

</style> 